//登陆处理模块

var async=require('async');
var config=require('../config');
var User=require('../model/User');
var Shop=require('../model/Shop');
var Food=require('../model/Food');
var Order=require('../model/Order');
var Time=require('../utils/Time');
var redis=require('../model/redis');

//获取菜单列表
var getFoodList=function(data,callback){
	Food.all(function(err,foods){
		if(err) return callback(err);
		data["foods"]=[];
		for(var i=0;i<foods.length;i++){
			data["foods"].push(JSON.parse(foods[i]));
		}
		callback(null,data);
	});
};

//获取商家列表
var getShopList=function(data,callback){
	Shop.all(function(err,shopes){
		if(err) return callback(err);
		data["shopes"]=[];
		for(var i=0;i<shopes.length;i++){
			data["shopes"].push(JSON.parse(shopes[i]));
		}
		callback(null,data);
	})
};

//获取用户列表
var getUserList=function(callback){
	User.all(function(err,users){
		if(err) return callback(err);
		var data={};
		data["users"]=[];
		for(var i=0;i<users.length;i++){
			data["users"].push(JSON.parse(users[i]));
		}
		callback(null,data);
	})
}

//获取菜单列表
var getFoodList=function(data,callback){
	Food.all(function(err,foods){
		if(err) return callback(err);
		data["foods"]=[];
		for(var i=0;i<foods.length;i++){
			data["foods"].push(JSON.parse(foods[i]));
		}
		callback(null,data);
	});
};



//根据foodId获取菜单数据
var getFoodInfoById=function(foods,foodId){
	for(var i=0;i<foods.length;i++){
		if(parseInt(foods[i].id)==parseInt(foodId)){
			return foods[i];
		}
	}
	return null;
}

//根据userId获取user数据
var getUserInfoById=function(users,userId){
	for(var i=0;i<users.length;i++){
		if(parseInt(users[i].id)==parseInt(userId)){
			return users[i];
		}
	}
	return null;
}


var sortOrderList=function(list,data){
	var orderNumMap={};
	var newOrderList=[];
	var count=0;
	var price=0;
	var foods=data["foods"]||[];
	var users=data["users"]||[];

	for(var i=0;i<list.length;i++){
		if(orderNumMap[list[i].foodId]) orderNumMap[list[i].foodId]++;
		else orderNumMap[list[i].foodId]=1;
	}
	for(var key in orderNumMap){
		var foodInfo=getFoodInfoById(foods,key);
		var obj={};
		obj["foodId"]=key;
		obj["foodName"]=foodInfo.name;
		obj["foodNum"]=parseInt(orderNumMap[key]);
		obj["onePrice"]=foodInfo.price;
		obj["price"]=foodInfo.price*obj["foodNum"];
		newOrderList.push(obj);
		count+=parseInt(orderNumMap[key]);
		price+=obj["price"];
	}
	data["foodOrderList"]=newOrderList;
	data["count"]=count;
	data["money"]=price;
}

var sortOrderListByUid=function(list,data){
	//[ { id: '1', order: '1,2' }, { id: '2', order: '1,2' } ]
	var foods=data["foods"]||[];
	var users=data["users"]||[];
	var userOrderList=[];
	for(var i=0;i<list.length;i++){
		var uid=parseInt(list[i].id);
		var orders=list[i].order.split(',');
		var orderTime=list[i].time;
		var ufoods=[];
		var ufoodsCount=0;
		var ufoodsMoney=0;
		var ufoodNum={};
		for(var j=0;j<orders.length;j++){
			if(ufoodNum[orders[j]]) ufoodNum[orders[j]]++;
			else ufoodNum[orders[j]]=1;
		}
		for(var key in ufoodNum){
			var foodInfo=getFoodInfoById(foods,key);
			var foodName=foodInfo.name;
			var foodNum=parseInt(ufoodNum[key]);
			var foodOrder=foodName+"*"+foodNum;
			ufoods.push(foodOrder);
			ufoodsCount+=parseInt(ufoodNum[key]);
			ufoodsMoney+=foodInfo.price*foodNum;
	    }
	    var obj={};
	    obj["uid"]=uid;
	    obj["uname"]=getUserInfoById(users,uid).name;
	    obj["orders"]=ufoods.toString();
	    obj["orderNum"]=ufoodsCount;
	    obj["orderMoney"]=ufoodsMoney;
	    obj["orderTime"]=orderTime;
	    userOrderList.push(obj);
	}
	
	data["userOrderList"]=userOrderList;
}



//登入验证
exports.login=function(req,res){
	var result={},email= req.body.email.trim();
	if(email==''){
		result["code"]=0;
		result["msg"]="邮箱不能为空";
		return res.send(result);

	}
	else{
		User.getUserInfoByMail(email,function(err,user){
			if(user){
				req.session.user=user;
				result["code"]=1;
				result["msg"]="登陆成功";

				var data={};
				data["isExpire"]=!Time.isInValidTime();
				data["success"]=true;
				data["foods"]=[];
				data["shopes"]=[];
				data["name"]=user.name||'';
				var userId=user.id;
				var key="order:"+userId;
				//获取用户订单
				var getUserOrder=function(callback){
					redis.exists(key,function(err,reply){
						if(err){
							data["code"]=404;
							data["success"]=false;
							data["msg"]="缓存操作失败!";
							return res.send(data);
						}
						else{
						    //key已经存在
						    if(reply==1){
						    	data["success"]=false;
							    data["msg"]="亲，您已经点餐了,记得主动向管理员付款哟！";
						    }
					    }
					    if(data["isExpire"]){
					    	data["success"]=false;
						    data["msg"]=" 亲,不好意思,非点餐时间无法下单,请记得准时点餐哟！";
					    }
					    callback(null,data); 
				    });
				};
				async.waterfall([getUserOrder,getFoodList,getShopList],function(err,_data){
					data=_data||data;
					for(var key in data){
						result[key]=data[key];
					}
					return res.send(result);
				});
			}
			else{
				result["code"]=2;
				result["msg"]="账户错误";
				return res.send(result);
			}
		});
	}
}

//获取菜单数据
exports.foods=function(req,res){
	//页面渲染数据
	var data={};
	data["isExpire"]=!Time.isInValidTime();
	data["code"]=1;
	data["success"]=true;
	data["msg"]="获取数据成功";
	data["foods"]=[];
	data["shopes"]=[];

	if(!req.session.user){
		data["code"]=2;
		data["msg"]="请先登陆!";
		return res.send(data);
	}
	data["name"]=req.session.user.name||'';

	var userId=req.session.user.id;
	var key="order:"+userId;
	//获取用户订单
	var getUserOrder=function(callback){
		redis.exists(key,function(err,reply){
			if(err){
				data["code"]=404;
				data["success"]=false;
				data["msg"]="缓存操作失败!";
				return res.send(data);
			}
			else{
			    //key已经存在
			    if(reply==1){
			    	data["code"]=1;
			    	data["success"]=false;
			    	data["msg"]="亲，您已经点餐了,记得主动向管理员付款哟！";
			    }
			}
			if(data["isExpire"]){
				data["success"]=false;
				data["msg"]=" 亲,不好意思,非点餐时间无法下单,请记得准时点餐哟！";
			}
			callback(null,data); 
		});
	};

	async.waterfall([getUserOrder,getFoodList,getShopList],function(err,result){
		data=result||data;
		return res.send(data);
	});
}

//获取订餐结果
exports.result=function(req,res){
	var data={};
	data["name"]=req.session.user.name;
	data["isAdmin"]=req.session.user.isAdmin;
	data["foodOrderList"]=[];
	data["userOrderList"]=[];
	data["count"]=0;
	data["money"]=0;


	//订单数据
	var getOrderList=function(data,callback){
		var foods=data["foods"]||[];
		var users=data["users"]||[];
		Order.getOrderList(function(err,result){
		    //[ { id: '1', order: '1,2'，time:'2012' }, { id: '2', order: '1,2',time:'2012' } ]
		    if(err) return callback(err);
		    result=result||[];
		    var list=[];
		    for(var i=0;i<result.length;i++){
		    	var uid=parseInt(result[i].id);
		    	var orders=result[i].order.split(',');
		    	var orderTime=result[i].time;
		    	var orderMap={};
		    	for(var j=0;j<orders.length;j++){
		    		var item=new Order(users,foods,uid,orders[j],orderTime);
		    		list.push(item);
		    	}
		    }

		    data["orders"]=list;
		    data["name"]=req.session.user.name;
		    data["isAdmin"]=req.session.user.isAdmin;
		    data["uid"]=req.session.user.id;
		    sortOrderList(list,data);
		    sortOrderListByUid(result,data);
		    callback(null,data);
		});
	};

	async.waterfall([getUserList,getFoodList,getOrderList],function(err,result){
		data=result||data;
		return res.send(data);
	});
}

//获取订餐结果
exports.resultView=function(req,res){
	var data={};
	data["foodOrderList"]=[];
	data["userOrderList"]=[];
	data["count"]=0;
	data["money"]=0;


	//订单数据
	var getOrderList=function(data,callback){
		var foods=data["foods"]||[];
		var users=data["users"]||[];
		Order.getOrderList(function(err,result){
		    //[ { id: '1', order: '1,2'，time:'2012' }, { id: '2', order: '1,2',time:'2012' } ]
		    if(err) return callback(err);
		    result=result||[];
		    var list=[];
		    for(var i=0;i<result.length;i++){
		    	var uid=parseInt(result[i].id);
		    	var orders=result[i].order.split(',');
		    	var orderTime=result[i].time;
		    	var orderMap={};
		    	for(var j=0;j<orders.length;j++){
		    		var item=new Order(users,foods,uid,orders[j],orderTime);
		    		list.push(item);
		    	}
		    }

		    data["orders"]=list;
		    sortOrderList(list,data);
		    sortOrderListByUid(result,data);
		    callback(null,data);
		});
	};

	async.waterfall([getUserList,getFoodList,getOrderList],function(err,result){
		data=result||data;
		return res.render('api/result',data);
	});
}


